from django.shortcuts import render
from rest_framework.response import Response
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
# Create your views here.
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer


class QQLoginURLView(APIView):

    def get(self, request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'
        # 构建跳转链接
        # 1.生成qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)

        # 2.调用生成url方法
        login_url = qq.get_qq_url()

        # 3.返回结果
        return Response({
            'login_url': login_url
        })


class OauthView(CreateAPIView):
    # 绑定openid和获取openid
    serializer_class = OauthSerializer

    # 获取openid
    def get(self, request):
        # 获取前端传递的code
        code = request.query_params.get('code')
        if code is None:
            return Response(
                {'errors': '缺少code值'},
                status=400
            )
        # 通过code值请求qq服务器获取access_token值
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='/')
        access_token = qq.get_access_token(code)

        # 通过access_token值请求qq服务器获取openid值
        openid = qq.get_open_id(access_token)

        # 判断openid是否和美多用户绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未绑定,绑定openid
            tjs = TJS(settings.SECRET_KEY, 300)
            data = tjs.dumps({
                'openid': openid
            }).decode()

            return Response({
                'access_token': data
            })

        # 如果绑定,则登陆成功
        else:
            # 获取用户对象
            user = qq_user.user

            # 生成token值
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

